//------------------------------------------------------------------------------
//
//   author: 小兵（aosnow@yeah.net）
//   create: 2012-5-29 下午22:36:19
//    class: ImageLoader - 图片加载类
//
//------------------------------------------------------------------------------

package starfire.rpc.loader.elements
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.system.SecurityDomain;
	
	import starfire.rpc.URL;
	import starfire.rpc.loader.LoadMessage;
	import starfire.rpc.loader.LoadState;

	[ExcludeClass]
	public class ImageLoader extends LoaderBase
	{
		protected var loader:Loader;
		protected var context:LoaderContext;

		public function ImageLoader( message:LoadMessage )
		{
			super( message );
		}

		override public function canHandleResource():Boolean
		{
			if( super.message )
			{
				var url:URL = new URL( super.message.url );
				return ( url.path.search( /\.gif$|\.jpeg$|\.jpg$|\.png$/i ) != -1 );
			}

			return false;
		}

		override protected function executeLoad( message:LoadMessage ):void
		{
			var urlReq:URLRequest = new URLRequest( message.url );

			// 图片加载初始化
			loader = new Loader();
			toggleLoaderListeners( loader, true );

			// 安全设置
			context = new LoaderContext();
			context.checkPolicyFile = true;

			// 开始加载数据
			try
			{
				updateLoadState( LoadState.LOADING );
				loader.load( urlReq, context );
			}
			catch( ioError:IOError )
			{
				IOErrorHandler( null, ioError.message );
			}
			catch( securityError:SecurityError )
			{
				securityErrorHandler( null, securityError.message );
			}
		}

		override protected function executeUnload( message:LoadMessage ):void
		{
			updateLoadState( LoadState.UNLOADING );
			loader = null;
			context = null;
			updateLoadState( LoadState.UNINITIALIZED );
		}

		override protected function loadCompleteHandler( event:Event ):void
		{
			toggleLoaderListeners( loader, false );

			var data:BitmapData;

			// 保存数据.
			// 图片文件数据保存方式为 bitmapData 数据 
			try
			{
				data = Bitmap( loader.content ).bitmapData;
				saveCache( data );
			}
			catch( e:Error )
			{
				return;
			}
			
			message.result = data;
			updateLoadState( LoadState.READY );
			
			// 执行回调函数
			if( complete is Function )
			{
				complete( message );
			}
		}
	}
}
